const Koa = require('koa')
const Koastatic = require('koa-static')
const favicon = require('koa-favicon')
// const mount = require('koa-mount')
const session = require('koa-session')
const bodyParser = require('koa-bodyparser')
const views = require('koa-views')
const path = require('path')
const config = require('./config')
const utils = require('./utils')
const router = require('./routes')
const common = require('./middleware/common')
const requestLog = require('./middleware/request-log')
const hanldeError = require('./middleware/handle-error')
const cors = require('./middleware/cors')
const app = new Koa()

app.keys = ['123456789']

app.use(cors)
app.use(hanldeError)
app.use(common)
app.use(requestLog)

// favicon
app.use(favicon(path.resolve(__dirname, '../public/favicon.ico')))

// static
app.use(Koastatic(path.resolve(__dirname, '../public'), {
  maxage: 24 * 60 * 60 * 1000
}))

// views
app.use(views(path.resolve(__dirname, '../views'), {
  map: { html: 'ejs' }
}))

// session
app.use(session({
  cookie: { secure: false, maxAge: 86400000 }
  // store: RedisStore(redisConf.session)
}, app))

// body
app.use(bodyParser())

router.all('*', ctx => {
  ctx.status = 404
  ctx.body = '404 Not Found!'
})

// router
app.use(router.routes(), router.allowedMethods())

// handle error
app.on('error', (err, ctx) => {
  console.error(err)
  ctx.status = 500
  ctx.body = { name: err.name, message: err.message }
})

app.listen(config.port, () => {
  console.log('Server On:', config.port)
  console.log('Server ENV:', config.env)
  console.log('Server At:', utils.idate().format())
})

module.exports = app
